package com.ycyoes.test.hollis.concurrent.inorder;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureThreadExecute {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建CompletableFuture对象
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(new MyThreadCompletableFuture("T1"));

        // 等待线程T1完成
        future1.join();

        // 创建CompletableFuture对象
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(new MyThreadCompletableFuture("T2"));

        // 等待线程T2完成
        future2.join();

        // 创建CompletableFuture对象
        CompletableFuture<Void> future3 = CompletableFuture.runAsync(new MyThreadCompletableFuture("T3"));

        // 等待线程T3完成
        future3.join();

        //--------------优化----------------
        // 创建CompletableFuture对象
//        CompletableFuture<Void> future = CompletableFuture.runAsync(new MyThreadCompletableFuture("T1")).thenRun(new MyThreadCompletableFuture("T2")).thenRun(new MyThreadCompletableFuture("T3"));
//        future.get();
    }
}

class MyThreadCompletableFuture implements Runnable {
    private String name;

    public MyThreadCompletableFuture(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        try {
            // 模拟执行任务
            Thread.sleep(1000);
            System.out.println(name + " is Running.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
